import { 
Icon, 
Tooltip, 
Button, 
Popover, 
ActionList , 
OptionList , 
LegacyCard ,
TextField ,
Select ,
} from "@shopify/polaris";
import { useState,useCallback, useEffect} from "react";
import {
  MagicMinor,
  ChevronDownMinor,
  BoldMinor,
  ItalicMinor,
  UnderlineMajor,
  TextColorMinor,
  TextAlignmentLeftMajor,
  LinkMinor,
  ImageWithTextOverlayMajor,
  PlayCircleMajor,
  HorizontalDotsMinor,
  EmbedMinor,
  InfoMinor,
  TextAlignmentCenterMajor,
  TextAlignmentRightMajor,
  ListMinor,
  OrderedListMinor,
  OutdentMinor,
  IndentMinor,
  AnalyticsTableMinor,
  CircleTickOutlineMinor,
  DropdownMinor,
} from "@shopify/polaris-icons";
import "./index.css";
import styled from "./index.module.less";

import { Color } from "@tiptap/extension-color";
import ListItem from "@tiptap/extension-list-item";
import TextStyle from "@tiptap/extension-text-style";
import { EditorContent, useEditor } from "@tiptap/react";
import StarterKit from "@tiptap/starter-kit";
import React from "react";
import Underline from '@tiptap/extension-underline'
import Document from '@tiptap/extension-document'
import Gapcursor from '@tiptap/extension-gapcursor'
import Paragraph from '@tiptap/extension-paragraph'
import Table from '@tiptap/extension-table'
import TableCell from '@tiptap/extension-table-cell'
import TableHeader from '@tiptap/extension-table-header'
import TableRow from '@tiptap/extension-table-row'
import Text from '@tiptap/extension-text'
import Link from '@tiptap/extension-link'
import TextAlign from '@tiptap/extension-text-align'

import ModalZP from "./modalZP"
import ModalSP from "./modalSP"
// interface Props {
//   editor: any;
// }

const MenuBar = ({ editor , MTWJs}) => {

  const [selectedSCWB, setSelectedSCWB] = useState([]);
  const [popoverActiveSCWB, setPopoverActiveSCWB] = useState(false);
  const togglePopoverActiveSCWB = () => {
    setPopoverActiveSCWB((popoverActiveSCWB) => !popoverActiveSCWB);
  };
  const activatorSCWB = (
    <Tooltip content="生成文本">
      <div className={styled.Btn1} onClick={togglePopoverActiveSCWB}>
        <Icon source={MagicMinor} color="highlight"></Icon>
        <Icon source={ChevronDownMinor}></Icon>
      </div>
    </Tooltip>
  );

  const [selectedGSSZ, setSelectedGSSZ] = useState([]);
  const [popoverActiveGSSZ, setPopoverActiveGSSZ] = useState(false);
  const togglePopoverActiveGSSZ = () => {
    setPopoverActiveGSSZ((popoverActiveGSSZ) => !popoverActiveGSSZ);
  };
  const activatorGSSZ = (
    <Tooltip content="格式设置" >
      <div className={styled.Btn2} onClick={togglePopoverActiveGSSZ}>
        <div>段落</div>
        <div>
          <Icon source={ChevronDownMinor}></Icon>
        </div>
      </div>
    </Tooltip>
  );
  const [popoverActiveYS, setPopoverActiveYS] = useState(false);
  const togglePopoverActiveYS = () => {
    setPopoverActiveYS((popoverActiveYS) => !popoverActiveYS);
  };
  const activatorYS = (
    <Tooltip content="颜色">
      <div className={styled.btn3} onClick={togglePopoverActiveYS}>
        <Icon source={TextColorMinor}></Icon>
        <Icon source={ChevronDownMinor}></Icon>
      </div>
    </Tooltip>
  );
  const [popoverActiveDQFS, setPopoverActiveDQFS] = useState(false);
  const togglePopoverActiveDQFS = () => {
    setPopoverActiveDQFS((popoverActiveDQFS) => !popoverActiveDQFS);
  };
  const activatorDQFS = (
    <Tooltip content="对齐方式">
      <div className={styled.Btn4} onClick={togglePopoverActiveDQFS}>
        <Icon source={TextAlignmentLeftMajor}></Icon>
        <Icon source={ChevronDownMinor}></Icon>
      </div>
    </Tooltip>
  );
  const [popoverActive, setPopoverActive] = useState(false);
  const togglePopoverActive = () => {
    setPopoverActive((popoverActive) => !popoverActive);
  };
  const activator = (
    <div className={styled.btn6} onClick={togglePopoverActive}>
      <Icon source={HorizontalDotsMinor}></Icon>
    </div>
  );
  const [popoverActiveCRBG, setPopoverActiveCRBG] = useState(false);
  const togglePopoverActiveCRBG = () => {
    setPopoverActiveCRBG((popoverActiveCRBG) => !popoverActiveCRBG);
  };
  const activatorCRBG = (
    <div onClick={togglePopoverActiveCRBG} className={styled.ICONs}><Icon source={AnalyticsTableMinor}></Icon><Icon source={DropdownMinor}></Icon></div>
  );
  

  //生成产品
  const [value, setValue] = useState('');

  const handleChange = 
    (newValue) => {setValue(newValue)}

    const [selected, setSelected] = useState('ZYD');

  const handleSelectChange = 
    (value) => {setSelected(value)}

  const options = [
    {label: '专业的', value: 'ZYD'},
    {label: '自定义', value: 'ZDY'},
    {label: '大胆的', value: 'DDD'},
    {label: '好玩的', value: 'HWD'},
    {label: '精致的', value: 'JZD'},
    {label: '有说服力的', value: 'YSFLD'},
    {label: '有帮助的', value: 'YBZD'},
  ];

  const [valueTSSM, setValueTSSM] = useState('');

  const handleChangeTSSM = 
    (newValue) => {setValueTSSM(newValue)}

  const [valueZDYJD, setValueZDYJD] = useState('');

  const handleChangeZDYJD = 
    (newValue) => {setValueZDYJD(newValue)}

// modal组件显示
const [ZPSHOW, setZPSHOW] = useState(false);
const [SPSHOW, setSPSHOW] = useState(false);

    const setLink = useCallback(() => {
      const previousUrl = editor.getAttributes('link').href
      const url = window.prompt('URL', previousUrl)
      // cancelled
      if (url === null) {
        return
      }
      // empty
      if (url === '') {
        editor.chain().focus().extendMarkRange('link').unsetLink()
          .run()
        return
      }
      // update link
      editor.chain().focus().extendMarkRange('link').setLink({ href: url })
        .run()
    }, [editor])
  if (!editor) {
    return null;
  }

  return (
    <div className={styled.TopButton}>
      <div className={styled.Margin}>
        <Popover
          active={popoverActiveSCWB}
          activator={activatorSCWB}
          autofocusTarget="first-node"
          onClose={togglePopoverActiveSCWB}
        >
          <LegacyCard >
            <div className={styled.SCCP}>
                <div className={styled.sccptop}>
                  <div>生产产品描述</div>
                  <div><Icon source={InfoMinor} color="subdued"></Icon></div>
                </div>
                <div className={styled.Content}>
                  <div className={styled.GNGJZ}>
                    <div className={styled.gngjz}>
                      <TextField
                        label="功能和关键字"
                        value={value}
                        onChange={handleChange}
                        autoComplete="off"
                        placeholder="有机棉,宽松裁剪"
                        multiline={3}
                      />
                    </div>
                  </div>
                  <div className={styled.SEL}>
                    <Select
                      label="基调"
                      options={options}
                      onChange={handleSelectChange}
                      value={selected}
                    />
                  </div>
                  {selected=="ZDY"?(<div className={styled.SEL}>
                    <TextField
                      label="自定义基调"
                      value={valueZDYJD}
                      onChange={handleChangeZDYJD}
                      autoComplete="off"
                      placeholder="例如:乐观的"
                    />
                  </div>):""}
                  <div className={styled.SEL}>
                    <TextField
                      label="特殊说明(可选)"
                      value={valueTSSM}
                      onChange={handleChangeTSSM}
                      autoComplete="off"
                      placeholder="例如：用表情符号替换部分字词"
                    />
                  </div>
                  <div className={styled.btnm} >
                    {!value&&<Button fullWidth icon={MagicMinor} disabled>生成文本</Button>}
                    {value&&<Button fullWidth icon={MagicMinor}>生成文本</Button>}
                  </div>
                </div>
            </div>
          </LegacyCard>
        </Popover>
      </div>
      <div className={styled.Margin}>
      <Popover
          active={popoverActiveGSSZ}
          activator={activatorGSSZ}
          autofocusTarget="first-node"
          onClose={togglePopoverActiveGSSZ}
      >
        <OptionList
            title=""
            onChange={setSelectedGSSZ}
            options={[
              {value: 'DL', label: <div onClick={() => editor.chain().focus().setParagraph().run()}  className={styled.title}>段落</div>},
              {value: 'T1', label: <div onClick={() => editor.chain().focus().toggleHeading({ level: 1 }).run()}  className={styled.title} style={{fontSize:'30px',fontWeight:700}}>标题1</div>},
              {value: 'T2', label: <div onClick={() => editor.chain().focus().toggleHeading({ level: 2 }).run()} className={styled.title} style={{fontSize:'22px',fontWeight:700}}>标题2</div>},
              {value: 'T3', label: <div onClick={() => editor.chain().focus().toggleHeading({ level: 3 }).run()} className={styled.title} style={{fontSize:'18px',fontWeight:700}}>标题3</div>},
              {value: 'T4', label: <div onClick={() => editor.chain().focus().toggleHeading({ level: 4 }).run()} className={styled.title} style={{fontSize:'15px',fontWeight:700}}>标题4</div>},
              {value: 'T5', label: <div onClick={() => editor.chain().focus().toggleHeading({ level: 5 }).run()} className={styled.title} style={{fontSize:'13px',fontWeight:700}}>标题5</div>},
              {value: 'T6', label: <div onClick={() => editor.chain().focus().toggleHeading({ level: 6 }).run()} className={styled.title} style={{fontSize:'12px',fontWeight:700}}>标题6</div>},
              {value: 'KYY', label: <div onClick={() => editor.chain().focus().toggleBlockquote().run()} className={styled.title+" "+styled.title1}>块引用</div>},
            ]}
            selected={selectedGSSZ}
          />
      </Popover>
      </div>
      <div className={styled.Margin}>
        <div className={styled.Btn3}>
          <Tooltip content="粗体">
            <div 
            className={styled.btn3s} 
            onClick={() => editor.chain().focus().toggleBold().run()}
            disabled={!editor.can().chain().focus().toggleBold().run()}
            >
              <Icon source={BoldMinor}></Icon>
            </div>
          </Tooltip>
          <Tooltip content="斜体">
            <div 
            className={styled.btn3s}
            onClick={() => editor.chain().focus().toggleItalic().run()}
            disabled={!editor.can().chain().focus().toggleItalic().run()}
            >
              <Icon source={ItalicMinor}></Icon>
            </div>
          </Tooltip>
          <Tooltip content="下划线">
            <div 
            className={styled.btn3s}
            onClick={() => editor.chain().focus().toggleUnderline().run()}
            >
              <Icon source={UnderlineMajor}></Icon>
            </div>
          </Tooltip>
          <Popover
              active={popoverActiveYS}
              activator={activatorYS}
              autofocusTarget="first-node"
              onClose={togglePopoverActiveYS}
          >
            <div className={styled.colorXZQ}>
              <input
                type="color"
                onInput={event => editor.chain().focus().setColor(event.target.value).run()}
                value={editor.getAttributes('textStyle').color}
                data-testid="setColor"
              />
            </div>
          </Popover>
          
        </div>
      </div>
      <div className={styled.Margin}>
        <Popover
            active={popoverActiveDQFS}
            activator={activatorDQFS}
            autofocusTarget="first-node"
            onClose={togglePopoverActiveDQFS}
        >
          <OptionList
            title=""
            onChange={setSelectedGSSZ}
            options={[
              {value: 'DL', label: <Tooltip content="左对齐"><div onClick={() => editor.chain().focus().setTextAlign('left').run()}><Icon source={TextAlignmentLeftMajor}></Icon></div></Tooltip>},
              {value: 'T1', label: <Tooltip content="居中对齐"><div onClick={() => editor.chain().focus().setTextAlign('center').run()}><Icon source={TextAlignmentCenterMajor}></Icon></div></Tooltip>},
              {value: 'T2', label: <Tooltip content="右对齐"><div onClick={() => editor.chain().focus().setTextAlign('right').run()}><Icon source={TextAlignmentRightMajor}></Icon></div></Tooltip>},
            ]}
            selected={selectedGSSZ}
          />
        </Popover>
      </div>
      <div className={styled.Margin}>
        <div className={styled.Btn5}>
          <Tooltip content="插入链接">
            <div className={styled.btn5} onClick={setLink}>
              <Icon source={LinkMinor}></Icon>
            </div>
          </Tooltip>
          <Tooltip content="插入图片" >
            <div className={styled.btn5} onClick={()=>{setZPSHOW(!ZPSHOW)}}>
              <Icon source={ImageWithTextOverlayMajor}></Icon>
            </div>
          </Tooltip>
          <Tooltip content="插入视频" >
            <div className={styled.btn5} onClick={()=>{setSPSHOW(!SPSHOW)}}>
              <Icon source={PlayCircleMajor}></Icon>
            </div>
          </Tooltip>
        </div>
      </div>
      <div className={styled.Margin1}>
        <div className={styled.Btn6}>
          <Popover
              active={popoverActive}
              activator={activator}
              autofocusTarget="first-node"
              onClose={togglePopoverActive}
          >
            <div className={styled.GDCZ}>
              <Tooltip content="项目符号列表">
                <div className={styled.ICON} onClick={() => editor.chain().focus().toggleBulletList().run()}><Icon source={ListMinor}></Icon></div>
              </Tooltip>
              <Tooltip content="编号列表">
                <div className={styled.ICON} onClick={() => editor.chain().focus().toggleOrderedList().run()}><Icon source={OrderedListMinor}></Icon></div>
              </Tooltip>
              <Tooltip content="向左缩进">
                <div onClick={() => editor.commands.joinBackward()} className={styled.ICON} ><Icon source={OutdentMinor}></Icon></div>
              </Tooltip>
              <Tooltip content="缩进">
                <div onClick={() => editor.commands.joinForward()} className={styled.ICON+" "+styled.Right}><Icon source={IndentMinor}></Icon></div>
              </Tooltip>
              <Tooltip content="插入表格">
              <Popover
                active={popoverActiveCRBG}
                activator={activatorCRBG}
                autofocusTarget="first-node"
                onClose={togglePopoverActiveCRBG}
              >
                <OptionList
                  title=""
                  onChange={setSelectedGSSZ}
                  options={[
                    {value: 'CRBG', label:<div onClick={() => editor.chain().focus().insertTable({ rows: 3, cols: 3, withHeaderRow: true }).run()}>插入表格</div> },
                    {value: 'SFCRH', label: <div onClick={() => editor.chain().focus().addRowBefore().run()}>在上方插入行</div>},
                    {value: 'XFCRH', label: <div onClick={() => editor.chain().focus().addRowAfter().run()}>在下方插入行</div>},
                    {value: 'SFCRL', label: <div onClick={() => editor.chain().focus().addColumnBefore().run()}>在之前插入列</div>},
                    {value: 'XFCRL', label: <div onClick={() => editor.chain().focus().addColumnAfter().run()}>在之后插入列</div>},
                    {value: 'SCH', label: <div onClick={() => editor.chain().focus().deleteRow().run()}>删除行</div>},
                    {value: 'SCL', label: <div onClick={() => editor.chain().focus().deleteColumn().run()}>删除列</div>},
                    {value: 'SCBG', label: <div onClick={() => editor.chain().focus().deleteTable().run()}>删除表格</div>},
                  ]}
                  selected={selectedGSSZ}
                />
              </Popover>
              </Tooltip>
              <Tooltip content="清除格式">
                <div className={styled.Padding} onClick={() => {editor.chain().focus().unsetAllMarks().run() ; editor.chain().focus().clearNodes().run()}} >
                  <div className={styled.ICON}><Icon source={CircleTickOutlineMinor}></Icon></div>
                </div>
              </Tooltip>
            </div>
          </Popover>
          <Tooltip content="显示HTML">
            <div className={styled.btn6} onClick={() => editor.chain().focus().toggleCodeBlock().run()}>
              <Icon source={EmbedMinor}></Icon>
            </div>
          </Tooltip>
        </div>
      </div>
      <div>
        {/* 组件 */}
        {ZPSHOW && <ModalZP MTWJs={MTWJs} ZPSHOW={ZPSHOW} setZPSHOW={setZPSHOW}/>}
        {SPSHOW && <ModalSP SPSHOW={SPSHOW} setSPSHOW={setSPSHOW}/>}
        {/* 组件 */}

      </div>
    </div>
  );
};

// interface Propss {
//   content: string;
// }

const App = ({ content , MTWJs }) => {
  const editor = useEditor({
    extensions: [
      Underline,
      Color,
      Link.configure({
        openOnClick: false,
      }),
      Document,
      Paragraph,
      Text,
      Gapcursor,
      Table.configure({
        resizable: true,
      }),
      TableRow,
      TableHeader,
      TableCell,
      TextAlign.configure({
        types: ['heading', 'paragraph'],
      }),
      Color.configure({ types: [TextStyle.name, ListItem.name] }),
      TextStyle.configure({ types: [ListItem.name] }),
      StarterKit.configure({
        bulletList: {
          keepMarks: true,
          keepAttributes: false, // TODO : Making this as `false` becase marks are not preserved when I try to preserve attrs, awaiting a bit of help
        },
        orderedList: {
          keepMarks: true,
          keepAttributes: false, // TODO : Making this as `false` becase marks are not preserved when I try to preserve attrs, awaiting a bit of help
        },
      }),
    ],
//     content: `<h2>
//   Hi there,
// </h2>
// <p>
//   this is a <em>basic</em> example of <strong>tiptap</strong>. Sure, there are all kind of basic text styles you’d probably expect from a text editor. But wait until you see the lists:
// </p>
// <ul>
//   <li>
//     That’s a bullet list with one …
//   </li>
//   <li>
//     … or two list items.
//   </li>
// </ul>
// <p>
//   Isn’t that great? And all of that is editable. But wait, there’s more. Let’s try a code block:
// </p>
// <pre><code class="language-css">body {
// display: none;
// }</code></pre>
// <p>
//   I know, I know, this is impressive. It’s only the tip of the iceberg though. Give it a try and click a little bit around. Don’t forget to check the other examples too.
// </p>
// <blockquote>
//   Wow, that’s amazing. Good work, boy! 👏
//   <br />
//   — Mom
// </blockquote>`,
    content: content,
  });



  return (
    <div>
      {/* 按钮 */}
      {content && <MenuBar editor={editor} MTWJs={MTWJs}/>}
      {/* 文本 */}
      <div>
        {/* <iframe style={{width:'100%',}} src="http://127.0.0.1:5500/src/components/RiceText/Content/index.html" frameborder="0"></iframe> */}
        <div className={styled.ContentSize}>
          {content && <EditorContent editor={editor} />}
        </div>
      </div>
      
    </div>
  );
};
export default App